package com.sqs.math;

/**
 * 
 * @author sqs
 *
 */
public final class Math {

	/**
	 * 不能实例化此类
	 */
	private Math() {

	}

	/**
	 * 求两个整数的最大公约数(Greatest common divisor)<br>
	 * 采用辗转相除法(即欧几里得算法)
	 * 
	 * @param a
	 *            positive integer
	 * @param b
	 *            positive integer
	 * @return
	 */
	public static int gcd(int a, int b) {
		if (a <= 0 || b <= 0) {
			throw new IllegalArgumentException("a and b must be positive!");
		}
		
		if(a==b){
			return a;
		}

		int temp1, temp2;
		if (a > b) {
			temp1 = a;
			temp2 = b;
		} else {
			temp1 = b;
			temp2 = a;
		}

		int temp3;

		while ((temp3 = temp1 % temp2) != 0) {
			temp1 = temp2;
			temp2 = temp3;
		}

		return temp2;
	}

	/**
	 * 求两个整数的最小公倍数(Least common multiple)<br>
	 * 利用公式 scm(a,b) = a*b / gcd(a,b)
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
	public static int scm(int a, int b) {
		if (a <= 0 || b <= 0) {
			throw new IllegalArgumentException("a and b must be positive!");
		}

		if (a == b) {
			return a;
		}

		return (a * b) / gcd(a, b);
	}

}
